/**
 *
 */
package susano.demo.action.company;

import java.text.SimpleDateFormat;
import java.util.Date;

import susano.common.util.BeanMap;
import susano.demo.service.company.CompanyService;
import susano.demo.service.company.EmployeeService;
import susano.presen.controller.Action;
import susano.presen.controller.Navigation;
import susano.presen.threadlocal.DateFormatLocal;
import susano.presen.validator.Validators;

/**
 * @author tanaka.akira
 *
 */
public class AddEmployeeAction extends Action {

	protected EmployeeService employeeService = new EmployeeService();
	protected CompanyService companyService = new CompanyService();

	private static final String DATE_FORMAT = "yyyy/MM/dd";

	/*
	 * (non-Javadoc)
	 *
	 * @see susano.presen.controller.Action#execute()
	 */
	@Override
	protected Navigation execute() {

		SimpleDateFormat sdf = DateFormatLocal.get(DATE_FORMAT);

		BeanMap employee = new BeanMap();
		employee.put("date", sdf.format(new Date()));
		employee.put("age", asInteger("age"));
		employee.put("name", asString("name"));

		// 保存
		if (!employeeService.put(employee, asString("parent"))) {
			errors.put("company", "従業員情報の保存に失敗しました。");
			return forward("index.jsp");
		}

		return redirect("/company/index");
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see susano.presen.controller.Action#init()
	 */
	@Override
	protected Navigation init() {
		show();
		requestScope("activeAccordionNo", 0);
		return forward("index.jsp");
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see susano.presen.controller.Action#validate()
	 */
	@Override
	protected Navigation validate() {
		Validators v = new Validators(request);
		v.add("name", v.required("氏名は必須です。"));
		v.add("age", v.required("年齢は必須です。"), v.integerType("年齢は数値で入力してください。"));
		v.add("parent", v.required("社名を選択してください。"));
		v.validate();

		requestScope("activeAccordionNo", 1);
		show();

		return forward("index.jsp");
	}

	private void show() {
		requestScope("companies", companyService.findAll());
	}
}
